<template>
  <a-input
    v-if="formItem.type == 'input' || formItem.type == 'phone'"
    v-model:value="formState[formItem.key]"
    :placeholder="formItem.setting.placeholder"
  />
  <a-textarea
    v-if="formItem.type == 'textarea'"
    v-model:value="formState[formItem.key]"
    :placeholder="formItem.setting.placeholder"
    :rows="3"
  />
  <a-input-number
    v-if="formItem.type == 'number'"
    v-model:value="formState[formItem.key]"
    :placeholder="formItem.setting.placeholder"
    :disabled="formItem.setting.disabled"
    style="width: 100%"
  />
  <a-input-number
    v-if="formItem.type == 'amount'"
    v-model:value="formState[formItem.key]"
    :placeholder="formItem.setting.placeholder"
    :disabled="formItem.setting.disabled"
    :precision="2"
    style="width: 100%"
  />
  <a-select
    v-if="formItem.type == 'radio'"
    :options="
      formItem.setting.options.map((item) => ({ label: item, value: item }))
    "
    v-model:value="formState[formItem.key]"
    :placeholder="formItem.setting.placeholder"
  />
  <a-select
    v-if="formItem.type == 'check'"
    mode="multiple"
    :options="
      formItem.setting.options.map((item) => ({ label: item, value: item }))
    "
    v-model:value="formState[formItem.key]"
    :placeholder="formItem.setting.placeholder"
  />
  <a-date-picker
    v-if="formItem.type == 'date'"
    v-model:value="formState[formItem.key]"
    :placeholder="formItem.setting.placeholder"
    :showTime="
      formItem.setting.dateType == 'datetime' ? { format: timeFormat } : false
    "
    :format="
      formItem.setting.dateType == 'datetime' ? dateTimeFormat : dateFormat
    "
    :valueFormat="
      formItem.setting.dateType == 'datetime' ? dateTimeFormat : dateFormat
    "
    style="width: 100%"
  />
  <a-time-picker
    v-if="formItem.type == 'time'"
    v-model:value="formState[formItem.key]"
    :placeholder="formItem.setting.placeholder"
    :format="timeFormat"
    :valueFormat="timeFormat"
    style="width: 100%"
  />
  <!-- 上传图片 -->
  <a-upload
    v-if="formItem.type == 'image'"
    :action="$utils.imgAction"
    :headers="{ 'org-token': $store.getters.token }"
    v-model:file-list="fileList"
    @change="handleUploadChange"
    :multiple="true"
    name="image"
    :data="{ dir: 'approval_image' }"
    accept="image/*"
    list-type="picture-card"
  >
    <div v-if="fileList.length < 9">
      <plus-outlined />
      <div>上传图片</div>
    </div>
  </a-upload>
  <a-upload
    v-if="formItem.type == 'file'"
    :action="$utils.fileAction"
    :headers="{ 'org-token': $store.getters.token }"
    :multiple="true"
    v-model:file-list="fileList"
    @change="handleUploadChange"
    name="file"
    :data="{ dir: 'approval_file' }"
  >
    <a-button v-if="fileList.length < 9">
      <upload-outlined></upload-outlined>
      上传文件
    </a-button>
  </a-upload>
</template>
<script>
import { defineComponent, reactive, ref, toRaw, toRefs, watch } from "vue";
import { UploadOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import moment from "moment";

export default defineComponent({
  name: "FormItem",
  components: { PlusOutlined, UploadOutlined },
  emits: ["change"],
  props: {
    content: {
      type: Object,
      default: () => ({}),
    },
    form: {
      type: Object,
      default: () => ({}),
    },
    list: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      formItem: {},
      formState: {},
      fileList: [],
    });

    // 表单数据同步到list中
    let changeCount = 0;
    let changeFlag = true;
    watch(
      () => state.formState[state.formItem.key],
      (value) => {
        // console.log(
        //   "-----------------监听表单值变化",
        //   state.formItem,
        //   toRaw(value)
        // );
        if (!changeCount) {
          changeCount = Object.keys(state.formState).length;
        } else {
          changeCount++;
        }
        state.formItem.value = value;
        // 处理 daterange
        if (
          state.formItem.originType == "daterange" &&
          state.formItem.typeKey != "duration"
        ) {
          handleDateRange();
        }
        if (changeFlag && changeCount > Object.keys(state.formState).length) {
          emit("change");
          changeFlag = false;
        }
      }
    );

    // daterange
    const handleDateRange = () => {
      const list = props.list.filter(
        (item) => item.originKey == state.formItem.originKey
      );
      const start = list.find((item) => item.typeKey == "start");
      const end = list.find((item) => item.typeKey == "end");
      if (start.value && end.value) {
        const duration = list.find((item) => item.typeKey == "duration");
        state.formState[duration.key] = duration.value = moment
          .duration(moment(end.value).diff(moment(start.value)))
          .asDays();
      }
    };

    // 上传文件的url列表同步到form数据中
    let timer = null;
    watch(
      () => state.fileList,
      (list) => {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(() => {
          console.log("-----------------fileList", toRaw(list));
          state.formItem.value = state.formState[state.formItem.key] = list.map(
            (item) => ({ name: item.name, url: item.url })
          );
          messageTip = false;
        }, 400);
      }
    );
    let messageTip = false;
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length > 9) {
        resFileList = resFileList.slice(0, 9);
        if (!messageTip) {
          message.warning("您最多只能上传9条数据！");
          messageTip = true;
        }
      }
      resFileList = resFileList.map((file) => {
        if (file.response) {
          if (file.response.code == 1000) {
            file.url = file.response.data.fileUrl;
            if (!state.formState.value) {
              state.formState.value = [];
            }
            state.formState.value.push({
              name: file.name,
              url: file.url,
            });
          } else {
            message.error(file.response.msg || "上传失败");
          }
        }
        return file;
      });
      state.fileList = resFileList;
    };
    const init = () => {
      state.formItem = props.content;
      state.formState = props.form;
    };
    init();
    return {
      dateFormat: "YYYY-MM-DD",
      timeFormat: "HH:mm",
      dateTimeFormat: "YYYY-MM-DD HH:mm",
      ...toRefs(state),
      handleUploadChange,
    };
  },
});
</script>

<style lang="less" scoped></style>
